import Request from './request'
import apiList from './apis.js'
import store from '@/ljshop/store/index.js'

const ljshopRequest = new Request();
export default function http(
	url,
	data = {},
	newHTTP = false,
	toastBefore = '', // 请求前加载提示
	toastAfter = true, // 请求后错误提示
) {
	let api = getApiPath(url);
	/* 请求之前拦截器 */
	ljshopRequest.interceptor.request((config, cancel) => {
		let token = uni.getStorageSync('token');
		if (api.auth && !token) {
			uni.hideLoading()
			throw (`暂未登录,已阻止此次API请求: '${api.url}'`);
		}
		token && ljshopRequest.setConfig(config => {
			config.header.token = token 
		})
		if (toastBefore !== '') {
			uni.showLoading({ 
				title: toastBefore,
				mask: true
			});
		}
		return config
	});

	/* 请求之后拦截器 */
	ljshopRequest.interceptor.response((response) => {
		uni.hideLoading();
		if (response.code === 0) {
			if (toastAfter) {
			}

		}

		// token过期注销
		if (response.code === 401) {
			store.dispatch('logout');
			throw (`登录已过期或注销,已阻止此次API请求: '${api.url}'`);
		}
		if (response.code && (response.code !== 1 && response.code !== '1' && response.code !== '200' && response.code !== 200)){
			uni.showToast({
				title:`${response.msg}`,
				icon:'none'
			})
		}
		return response
	})
	// data.secret = 'ia9j23j32f0wsk39m'
	return ljshopRequest.request({
		url: api.url,
		data,
		method: api.method,
		newHTTP: api.newHTTP,
		contentType: api.contentType,
	})

}

// 组装接口路径
function getApiPath(url) {
	let apiArray = url.split(".");
	let api = apiList;
	// console.log(api);
	apiArray.forEach(v => {
		api = api[v];
	});
	// console.info(api)
	return api;
}
